package basic

import (
	"os"
	"fmt"
	"path"
	"errors"
	"runtime"
	"path/filepath"
	"meman/sys/models/config"
	"github.com/BurntSushi/toml"
)

const (
	//配置文件默认位置
	CONFIGPATH = "/etc/event.toml"
)

var Config *config.Config

func init()  {
	config,err := ParseConfig()
	if err != nil {
		panic("init config!")
	}
	Config = config
}

/**
获取配置文件,返回配置文件对象
@return error | nil
 */
func ParseConfig() (*config.Config, error) {
	logger := Logger{}

	//获取配置文件的位置
	var configFile string
	if len(os.Args) > 1 {
		configFile = os.Args[1]
	}else {
		if runtime.GOOS == "windows" {
			clientPath, err := filepath.Abs(os.Args[0])
			if err != nil {
				logger.WriteMsg("error", fmt.Sprintf("Failed to get client ABS path: %v", err))
				return nil,errors.New(fmt.Sprintf("Failed to get client ABS path: %v", err))
			}
			configFile = path.Dir(clientPath) + string(os.PathListSeparator) + "config.toml"
		}else {
			configFile = CONFIGPATH
		}
	}

	//根据配置文件toml 转换成对象
	var conf config.Config
	if _, err := toml.DecodeFile(configFile, &conf); err != nil {
		logger.WriteMsg("error", fmt.Sprintf("Decode toml config err: %v", err))
		return nil, err
	}
	return &conf,nil
}
